package com.rainng.coursesystem.service.teacher;

import com.rainng.coursesystem.manager.teacher.TeacherStudentCourseManager;
import com.rainng.coursesystem.model.constant.AuditStatus;
import com.rainng.coursesystem.model.entity.StudentCourseEntity;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import com.rainng.coursesystem.service.BaseService;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("teacherStudentCourseService")
public class TeacherStudentCourseService extends BaseService {
    private final TeacherStudentCourseManager manager;

    public TeacherStudentCourseService(TeacherStudentCourseManager manager) {
        this.manager = manager;
    }

    public ResultVO getPage(Integer index, String studentName, String courseName, Integer status) {
        Integer teacherId = getUserId();
        return result(manager.getPage(index, teacherId, studentName, courseName, status));
    }

    public ResultVO audit(Integer studentCourseId, boolean approved) {
        Integer teacherId = getUserId();
        StudentCourseEntity studentCourse = manager.get(studentCourseId);
        if (studentCourse == null) {
            return failedResult("选课记录Id: " + studentCourseId + "不存在!");
        }

        // 只有课程的授课教师才能审核选课
        if (!manager.isCourseTeacher(studentCourse.getCourseId(), teacherId)) {
            return failedResult("您不是该课程的授课教师，无权审核");
        }

        studentCourse.setStatus(approved ? AuditStatus.APPROVED : AuditStatus.REJECTED);
        studentCourse.setAuditTime(new Date());
        studentCourse.setAuditTeacherId(teacherId);

        if (approved) {
            // 如果审核通过，增加课程已选人数
            manager.increaseCourseSelectedCount(studentCourse.getCourseId());
        }

        manager.update(studentCourse);
        return result(approved ? "审核通过" : "审核拒绝");
    }
} 